package cn.com.woxitech.dev.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import cn.com.woxitech.dev.common.APIResult;
import cn.com.woxitech.dev.common.APIResultFactory;
import cn.com.woxitech.dev.common.CodeUtils;
import cn.com.woxitech.dev.common.Const;
import cn.com.woxitech.dev.common.HttpClientUtils;
import cn.com.woxitech.dev.common.JSONUtils;
import cn.com.woxitech.dev.common.QiniuPhotoUploadUtils;
import cn.com.woxitech.dev.common.StrUtils;
import cn.com.woxitech.dev.model.Lecture;
import cn.com.woxitech.dev.model.QiniuUploadResult;
import cn.com.woxitech.dev.model.RoomManager;
import cn.com.woxitech.dev.model.WmChathistoryFetch;
import cn.com.woxitech.dev.model.gen.WeixinApiAccessToken;
import cn.com.woxitech.dev.model.gen.WmApp;
import cn.com.woxitech.dev.model.gen.WmLecture;
import cn.com.woxitech.dev.model.gen.WmLecturePage;
import cn.com.woxitech.dev.model.gen.WmRoom;
import cn.com.woxitech.dev.model.gen.WmUser;
import cn.com.woxitech.dev.service.AppService;
import cn.com.woxitech.dev.service.CatalogService;
import cn.com.woxitech.dev.service.LecturePageService;
import cn.com.woxitech.dev.service.LectureService;
import cn.com.woxitech.dev.service.OrganizationService;
import cn.com.woxitech.dev.service.PrivilegeService;
import cn.com.woxitech.dev.service.QiniuService;
import cn.com.woxitech.dev.service.RoomService;
import cn.com.woxitech.dev.service.SMSCodeService;
import cn.com.woxitech.dev.service.SettingService;
import cn.com.woxitech.dev.service.UserService;
import cn.com.woxitech.dev.service.WeixinService;
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncoderException;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.InputFormatException;

@RestController
@RequestMapping("/attachment")
public class AttachmentWJTController {
	@Autowired
	WeixinService weixinService;
	@Autowired
	SettingService settingService;
	@Autowired
	PrivilegeService privilegeService;
	@Autowired
	QiniuService qiniuService;
	@Autowired
	RoomService roomService;
	@Autowired
	LectureService lectureService;
	@Autowired
	LecturePageService lecturePageService;
	@Autowired
	UserService userService;
	@Autowired
	SMSCodeService smsCodeService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	CatalogService catalogService;	
	@Autowired
	AppService appService;

	@RequestMapping(value = "upload_audio/roomuuid/{roomuuid}", method = RequestMethod.POST)
	public APIResult upload_audio(HttpServletResponse response,HttpServletRequest request, @RequestParam("file") MultipartFile file,@PathVariable String roomuuid) {


		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			
			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/audio/";
//			filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = roomuuid + "_"+(new Date()).getTime();//+".amr";
			String filename = filebase + key;
			
			File f_path = new File(filebase);
			if(!f_path.exists()){
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if(!f_key.exists()){
				f_key.createNewFile();
			}
			
			FileOutputStream fos =new FileOutputStream(f_key);
					
			fos.write(bytes);
			
			fos.flush();
			fos.close();
			
			String web_path =  StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.WEB_HOSTNAME)) +"/attachment/audio/"+ key;
			String relative_path = "/attachment/audio/"+ key;
			
//			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
//			room.setLivecoverurl(relative_path);
//			this.roomService.updateByPrimaryKey(room);
			
			mp.put("key", key);
			mp.put("relative_path", relative_path);
			mp.put("path",web_path);
			
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
		
	}
	
	@RequestMapping(value = "upload_chatimg/roomuuid/{roomuuid}/userid/{userid}", method = RequestMethod.POST)
	public APIResult uploadChatImgToServer(HttpServletResponse response,HttpServletRequest request, @RequestParam("file") MultipartFile file, @PathVariable String roomuuid,@PathVariable String userid) {


		Map<String, Object> mp = new HashMap<String, Object>();
		try {
			if (file.isEmpty()) {
				return APIResultFactory.fail();
			}
			
			String filebase = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/img/";
//			filebase = filebase.replaceAll("\\", "\\\\");
			byte[] bytes = file.getBytes();
			String key = roomuuid + "_"+(new Date()).getTime();
			String filename = filebase + key;
			
			File f_path = new File(filebase);
			if(!f_path.exists()){
				f_path.mkdirs();
			}
			File f_key = new File(f_path, key);
			if(!f_key.exists()){
				f_key.createNewFile();
			}
			
			FileOutputStream fos =new FileOutputStream(f_key);
					
			fos.write(bytes);
			
			fos.flush();
			fos.close();
			
			String web_path =  StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.WEB_HOSTNAME)) +"/attachment/img/"+ key;
			String relative_path = "/attachment/img/"+ key;
			
//			WmRoom room = this.roomService.getRoomsByUuid(roomuuid);
//			room.setLivecoverurl(relative_path);
//			this.roomService.updateByPrimaryKey(room);
			
			mp.put("key", key);
			mp.put("relative_path", relative_path);
			mp.put("path",web_path);
			
			return APIResultFactory.success(mp);

		} catch (Exception e) {
			e.printStackTrace();
			return APIResultFactory.fail("");
		}
		
	}
	@RequestMapping(value="/audio/{audioId}",method=RequestMethod.GET)
	public void audio(HttpServletResponse response,HttpServletRequest request, @PathVariable String audioId) {

		response.setContentType("audio/amr");// 设置相应类型,告诉浏览器输出的内容为图片
//		response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
//		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("max-age", 360000); //cache保存为100小时
		
		String width = request.getParameter("w");
		String height = request.getParameter("h");
		String base = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/audio/";
		String path = base + audioId;
		InputStream reader = null;
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			byte[] bytes = new byte[1024];
			int len = 0;
		
            // 读取文件
            reader = new FileInputStream(path);

            while ((len = reader.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
        	try {
	            if (reader != null) {
	            	reader.close();
	            }
	            if (out != null){
	                out.close();
	            }
        	} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
		
	}
	
	

	@RequestMapping(value="/ppt/{pptdir}/{pptjpg}",method=RequestMethod.GET)
	public void pptjpg(HttpServletResponse response,HttpServletRequest request, @PathVariable String pptdir,@PathVariable String pptjpg) {

//		"/attachment/ppt/" + pptkey + "_dir/";
		
		response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
//		response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
//		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("max-age", 360000); //cache保存为100小时
		
		String path = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/ppt/"+pptdir+"/"+pptjpg+".jpg";
		
		InputStream reader = null;
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			byte[] bytes = new byte[1024];
			int len = 0;
		
            // 读取文件
            reader = new FileInputStream(path);

            while ((len = reader.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
        	try {
	            if (reader != null) {
	            	reader.close();
	            }
	            if (out != null){
	                out.close();
	            }
        	} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
		
	}
	
	@RequestMapping(value="/chatimg/{imgId}",method=RequestMethod.GET)
	public void chatimg(HttpServletResponse response,HttpServletRequest request, @PathVariable String imgId) {

		response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
//		response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
//		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("max-age", 360000); //cache保存为100小时
		
		String width = request.getParameter("w");
		String height = request.getParameter("h");
		String base = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/chatimg/";
		String path = base + imgId;
		InputStream reader = null;
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			byte[] bytes = new byte[1024];
			int len = 0;
		
            // 读取文件
            reader = new FileInputStream(path);

            while ((len = reader.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
        	try {
	            if (reader != null) {
	            	reader.close();
	            }
	            if (out != null){
	                out.close();
	            }
        	} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
		
	}
	@RequestMapping(value="/img/{imgId}",method=RequestMethod.GET)
	public void img(HttpServletResponse response,HttpServletRequest request, @PathVariable String imgId) {

		response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
//		response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
//		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("max-age", 360000); //cache保存为100小时
		
		String width = request.getParameter("w");
		String height = request.getParameter("h");
		String base = StrUtils.removeVirguleOfEnd(this.settingService.getSettingVal(Const.ATTACHMENT_PATH)) + "/img/";
		String path = base + imgId;
		InputStream reader = null;
		OutputStream out = null;
		try {
			out = response.getOutputStream();
			byte[] bytes = new byte[1024];
			int len = 0;
		
            // 读取文件
            reader = new FileInputStream(path);

            while ((len = reader.read(bytes)) > 0) {
                out.write(bytes, 0, len);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
        	try {
	            if (reader != null) {
	            	reader.close();
	            }
	            if (out != null){
	                out.close();
	            }
        	} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
		
	}
	
	
}
